﻿using System;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using ImageProcessor.Shared;
using ImageProcessor.Shared.ImageExtensions;

namespace ImageProcessor.Tim
{
    public class NoiseVM : ImageProcessorBaseVM
    {
        private ImageSource _resultImage;
        private double _chance;
        private static Random _random = new Random();

        public NoiseVM(MainViewModel mainVM) : base (mainVM)
        {
            Chance = 10;
        }

        public ImageSource ResultImage
        {
            get { return _resultImage; }
            private set
            {
                if(_resultImage == value)
                    return;
                _resultImage = value;
                OnPropertyChanged("ResultImage");
            }
        }

        public double Chance
        {
            get { return _chance; }
            set
            {
                if(_chance == value)
                    return;
                _chance = value;
                OnPropertyChanged("Chance");
            }
        }

        protected override void Execute(object obj)
        {
            var bitmap = new WriteableBitmap((BitmapSource) MainVM.SourceImage);
            
            bitmap.SetEachPixelColour(point=>
                                          {
                                              var pixelColor = bitmap.GetPixel(point.X, point.Y);
                                              if (_random.Next(0, 100) <= Chance)
                                                  return PixelColor.FromColor(Colors.Black);
                                              return PixelColor.FromColor(pixelColor);
                                          });

            ResultImage = bitmap;
        }

        protected override bool CanExecute(object obj)
        {
            return MainVM.SourceImage != null;
        }
    }
}